package com.study.security.filter;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.study.Util.CommonResponse;
import com.study.Util.ServletUtil;
import com.study.common.constants.BaseConstants;
import com.study.modules.saas.service.RoleService;
import com.study.modules.saas.service.UserService;
import com.study.security.domain.CurrentUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 重写security权限拦截
 */
@Slf4j
@Component
public class SecurityAuthFilter extends OncePerRequestFilter {

    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (request.getRequestURI().startsWith("/sa/login") || request.getRequestURI().startsWith("/sa/register")) {
            filterChain.doFilter(request, response);
            return;
        }

        String ticket = request.getHeader(BaseConstants.TOKEN);
        if (StringUtils.isNotBlank(ticket)) {
            CurrentUser currentUser = userService.getCurrentUserByToken(ticket);
            if (ObjectUtils.isNotNull(currentUser)) {
                Integer roleId = currentUser.getRoleId();
                if (roleId != null) {
                    List<String> collect = roleService.getRoleByRoleId(roleId)
                            .getMenuList()
                            .stream()
                            .map(menu -> menu == null ? "" : menu.getPermission())
                            .collect(Collectors.toList());
                    currentUser.setPermissions(collect); // 操作权限

                    UsernamePasswordAuthenticationToken authenticationToken =
                            new UsernamePasswordAuthenticationToken(currentUser, null, null);
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                    // 把认证的对象存储在Security的上下文中
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            } else {
                String message = JSON.toJSONString(CommonResponse.fail("已超时"));
                ServletUtil.senderString(HttpServletResponse.SC_UNAUTHORIZED,response,message);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}
